package org.zwt.view.impl;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.zwt.common.entity.HttpResponse;
import org.zwt.common.entity.ModelAndView;
import org.zwt.common.enumerate.HttpVersion;
import org.zwt.common.enumerate.ResponseStatus;
import org.zwt.view.IViewResolver;
import java.util.Date;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class SimpleViewResolver implements IViewResolver {
    private String prefix = "";
    private String suffix = "";


    @Override
    public HttpResponse resolve(ModelAndView mav) throws IOException {
        /*
         *1.从mav中获取视图信息
         **/
        String viewName = mav.getViewName();
        String viewPath = this.prefix + viewName + this.suffix;

        /*
         *2.从视图路径中，读取文件中的内容
         **/
        String content = this.readFile(viewPath);
        /*
         *3.使用Model,填充视图中的占位符
         **/
        for (String key : mav.getAttributeNames()) {
            content = content.replace("#{" + key + "}", mav.getAttribute(key));

        }
        /*
         *4.封装内容为HttpResponse对象
         **/
        HttpResponse httpResponse = new HttpResponse();
        httpResponse.setVersion(HttpVersion.HTTP_1_1);
        httpResponse.setStatus(ResponseStatus.OK);
        httpResponse.setHeader("Server", "MyServer");
        httpResponse.setHeader("Date",
                new Date().toString());
        httpResponse.setHeader("Content-Type", "text/html;charset=UTF-8");
        httpResponse.setHeader("Content-Length", String.valueOf(content.getBytes().length));
        httpResponse.setBody(content);
        return httpResponse;


    }


    private String readFile(String viewPath) throws IOException {
        StringBuffer buffer = new StringBuffer();

        InputStream is = Thread.currentThread().
                getContextClassLoader().getResourceAsStream(viewPath);
        if (is == null) {
            throw new IOException("找不到文件：" + viewPath);
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        reader.lines().forEach(buffer::append);
        reader.close();
        return buffer.toString();

    }
}
